package com.example.zhinongbao.utils;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.os.IBinder;
import android.util.Log;

public class MessagePassengerService extends Service {

    private static final String TAG = MessagePassengerService.class.getSimpleName();
    private static final String BROADCAST_ACTION_UPDATE = "com.goods.updata";
    private static final String BROADCAST_ACTION_PROCESSED = "com.goods.processed";

    private LocalBroadcastManager localBroadcastManager;
    private BroadcastReceiver localReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service is being created.");
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localReceiver = new LocalReceiver();
        IntentFilter filter = new IntentFilter(BROADCAST_ACTION_UPDATE);
        localBroadcastManager.registerReceiver(localReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service is starting.");
        // Perform initialization if necessary
        return Service.START_STICKY; // Or another appropriate return value
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        // This service does not bind to an activity, return null
        return null;
    }

    private class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "Received broadcast in service.");
            try {
                // Perform operations such as data update
                // ...

                // Notify TestActivity that the service has processed the message
                Intent localIntent = new Intent(BROADCAST_ACTION_PROCESSED);
                localBroadcastManager.sendBroadcast(localIntent);
            } catch (Exception e) {
                Log.e(TAG, "Error handling broadcast", e);
                // Handle exception appropriately
            }
        }
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "Service is being destroyed.");
        localBroadcastManager.unregisterReceiver(localReceiver);
        super.onDestroy();
    }
}